#include "ServerSocket.h"
#include "ServerReaderThread.h"

bool ServerSocket::ServerOpen(int port)
{
	m_Port=port;
	SDLNet_ResolveHost(&m_Ip,INADDR_ANY,port);
	m_Open=true;
	if(m_Ip.host == INADDR_NONE)
	{
		
		return false;
	}

	m_TcpSock = SDLNet_TCP_Open(&m_Ip);
	if(!m_TcpSock)
	{
		
		return false;
	}
	
	return true;
}

Socket* ServerSocket::Accept()
{
	TCPsocket s = SDLNet_TCP_Accept(m_TcpSock);
	
	if(!s)
	{
		return 0;
	}

	return new Socket(s);
}

Server::Server()
{}
Server::~Server()
{}
bool Server::Open(int port, int clients)
{
	m_Port =port;
	m_NumClients=clients;

	if(TheServer::Instance()->GetListener()->ServerOpen(port))
	{
		return true;
	}
	return false;
}
void Server::Broadcast(SockMessage& sm)
{
	Lock l(&m_Mutex);
	for(unsigned int i =0;i<m_NumClients;++i)
	{
		m_InSocks[i]->Send(sm);
	}
}
unsigned int Server::NumOfClients()
{
	Lock l(&m_Mutex);
	return m_InSocks.size();
}
Socket* Server::GetClient(int i)
{
	Lock l(&m_Mutex);
	return m_InSocks[i];
}
void Server::AddClient(Socket* s)
{
	Lock l(&m_Mutex);
	m_InSocks.push_back(s);
	ServerReaderThread* t = new ServerReaderThread(s,m_InSocks.size());
	t->Start();
}
ServerSocket* Server::GetListener()
{
	return &m_Listener;
}